package com.dianrui.fmi.community;

import android.content.Intent;
import android.net.Uri;
import android.support.design.widget.BottomSheetDialog;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.dianrui.fmi.Constant;
import com.dianrui.fmi.R;
import com.dianrui.fmi.activity.BaseActivity;
import com.dianrui.fmi.activity.BigImageActivity;
import com.dianrui.fmi.adapter.CommentunityInfoListAdapter;
import com.dianrui.fmi.adapter.NineAdapter;
import com.dianrui.fmi.bean.CommentInfoList;
import com.dianrui.fmi.bean.CommunitySubClass;
import com.dianrui.fmi.event.RfreshAnswer;
import com.dianrui.fmi.event.RfreshCommunity;
import com.dianrui.fmi.event.RfreshCommunityInfo;
import com.dianrui.fmi.event.RfreshFavorites;
import com.dianrui.fmi.event.RfreshQuestion;
import com.dianrui.fmi.interfaces.NineAdapter2OperationCallBack;
import com.dianrui.fmi.util.GlideUtil;
import com.dianrui.fmi.util.MyUtil;
import com.dianrui.fmi.util.OkHttpUtils;
import com.dianrui.fmi.util.StringUtils;
import com.dianrui.fmi.util.ToastUtil;
import com.dianrui.fmi.util.Url;
import com.dianrui.fmi.view.InnerGridView;
import com.dianrui.fmi.view.pulltoRefresh.PullToRefreshBase;
import com.dianrui.fmi.view.pulltoRefresh.PullToRefreshListView;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.share.Sharer;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.ShareDialog;
import com.google.gson.JsonObject;
import com.twitter.sdk.android.tweetcomposer.TweetComposer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 *
 */

public class CommuntiyInfoActivity extends BaseActivity implements NineAdapter2OperationCallBack {
    private CallbackManager callbackManager;
    private ShareDialog shareDialog;
    private String community_id;
    private int mPageIndex = 1;
    private CommentunityInfoListAdapter commentunityInfoListAdapter;
    private List<CommentInfoList> commentInfoLists = new ArrayList<>();

    @BindView(R.id.face)
    ImageView face;
    @BindView(R.id.like_img)
    ImageView likeImg;
    @BindView(R.id.nickname)
    TextView nickname;
    @BindView(R.id.create_time)
    TextView createTime;
    @BindView(R.id.contents)
    TextView contents;
    @BindView(R.id.all_comment_number)
    TextView allCommentNumber;
    @BindView(R.id.share_number)
    TextView shareNumber;
    @BindView(R.id.like_number)
    TextView likeNumber;
    @BindView(R.id.right_img)
    ImageView rightImg;
    @BindView(R.id.nine_view)
    InnerGridView innerGridView;
    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.community_info_list)
    PullToRefreshListView communityInfoList;

    @BindView(R.id.community_data_layout)
    LinearLayout communityDataLayout;
    @BindView(R.id.community_ino_nodata)
    LinearLayout communityInoNodata;


    @Override
    public int getContentViewId() {
        return R.layout.activity_community_info;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        if (getIntent() != null && getIntent().getExtras() != null) {
            community_id = getIntent().getStringExtra("community_id");
        }
        title.setText(getString(R.string.community_info_title));
        commentunityInfoListAdapter = new CommentunityInfoListAdapter(CommuntiyInfoActivity.this, commentInfoLists);
        communityInfoList.setAdapter(commentunityInfoListAdapter);
        getCommunityInfo();
        getCommentList(false);
        communityInfoList.setMode(PullToRefreshBase.Mode.BOTH);
        communityInfoList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                getCommentList(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                mPageIndex++;
                getCommentList(false);
            }
        });


        commentunityInfoListAdapter.setOnCommentunityClickListener(new CommentunityInfoListAdapter.CommentClickListener() {
            @Override
            public void Reply(String community_id, String comment_pid, String replyNames) {
                ReplyComment(community_id, comment_pid, replyNames);
            }

            @Override
            public void getSubComment(String commentId) {
                startActivity(new Intent(CommuntiyInfoActivity.this,CommentInfoActivity.class).putExtra("commentId",commentId));
            }
        });
        initFacebook();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RfreshCommunityInfo rfreshCommunityInfo) {
        getCommunityInfo();
        getCommentList(true);

    }


    private void getCommunityInfo() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("community_id", community_id);
        OkHttpUtils.getInstance().postWithMemberToken(Url.COMMUNITYDETAILS, jsonObject.toString(), new OkHttpUtils.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    if (communityInfoList != null) {
                        communityInfoList.onRefreshComplete();
                    }
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                GlideUtil.loadUserImageViewSize(getApplicationContext(), jsonObject.optJSONObject("data").optString("face"), face);
                                nickname.setText(jsonObject.optJSONObject("data").optString("nickname"));
                                createTime.setText(jsonObject.optJSONObject("data").optString("create_time"));
                                contents.setText(jsonObject.optJSONObject("data").optString("contents"));
                                allCommentNumber.setText(jsonObject.optJSONObject("data").optString("comment_number"));
                                shareNumber.setText(jsonObject.optJSONObject("data").optString("share_number"));
                                likeNumber.setText(jsonObject.optJSONObject("data").optString("collect_number"));
                                if (jsonObject.optJSONObject("data").optInt("is_collect") == 1) {
                                    likeImg.setImageResource(R.mipmap.collected);
                                } else {
                                    likeImg.setImageResource(R.mipmap.uncollected);
                                }
                                JSONArray jsonArray1 = jsonObject.optJSONObject("data").optJSONArray("picture");
                                List<String> picList = new ArrayList<>();
                                for (int j = 0; j < jsonArray1.length(); j++) {
                                    picList.add(jsonArray1.optString(j));
                                }

                                if (picList.size() > 0) {
                                    innerGridView.setAdapter(new NineAdapter(picList,CommuntiyInfoActivity.this));
                                    innerGridView.setVisibility(View.VISIBLE);
                                } else {
                                    innerGridView.setVisibility(View.GONE);
                                }



                                communityDataLayout.setVisibility(View.VISIBLE);
                                communityInoNodata.setVisibility(View.GONE);

                            } else {
                                if (communityInfoList != null) {
                                    communityInfoList.onRefreshComplete();
                                }
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    if (communityInfoList != null) {
                        communityInfoList.onRefreshComplete();
                    }
                    communityDataLayout.setVisibility(View.GONE);
                    communityInoNodata.setVisibility(View.VISIBLE);
                }
            }
        });

    }

    private void getCommentList(final boolean isRfresh) {
        if (isRfresh) {
            mPageIndex = 1;
        }
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("community_id", community_id);
        jsonObject.addProperty("p", mPageIndex);
        OkHttpUtils.getInstance().postWithMemberToken(Url.COMMENTINFO, jsonObject.toString(), new OkHttpUtils.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (communityInfoList != null) {
                    communityInfoList.onRefreshComplete();
                }
                if (isRfresh) {
                    commentInfoLists.clear();
                }
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {

                                JSONArray data = jsonObject.optJSONArray("data");
                                if (data.length() > 0) {
                                    for (int i = 0; i < data.length(); i++) {
                                        CommentInfoList commentInfoList = new CommentInfoList();
                                        commentInfoList.comment_id = data.optJSONObject(i).optString("comment_id");
                                        commentInfoList.contents = data.optJSONObject(i).optString("contents");
                                        commentInfoList.create_time = data.optJSONObject(i).optString("create_time");
                                        commentInfoList.community_id = data.optJSONObject(i).optString("community_id");
                                        commentInfoList.member_id = data.optJSONObject(i).optString("member_id");
                                        commentInfoList.nickname = data.optJSONObject(i).optString("nickname");
                                        commentInfoList.face = data.optJSONObject(i).optString("face");
                                        commentInfoList.subclass_count = data.optJSONObject(i).optInt("subclass_count");
                                        List<CommunitySubClass> comment_list = new ArrayList<>();
                                        JSONArray jsonArray1 = data.optJSONObject(i).optJSONArray("subclass");
                                        for (int j = 0; j < jsonArray1.length(); j++) {
                                            CommunitySubClass communitySubClass = new CommunitySubClass();
                                            communitySubClass.comment_id = jsonArray1.optJSONObject(j).optString("comment_id");
                                            communitySubClass.contents = jsonArray1.optJSONObject(j).optString("contents");
                                            communitySubClass.create_time = jsonArray1.optJSONObject(j).optString("create_time");
                                            communitySubClass.community_id = jsonArray1.optJSONObject(j).optString("community_id");
                                            communitySubClass.member_id = jsonArray1.optJSONObject(j).optString("member_id");
                                            communitySubClass.nickname = jsonArray1.optJSONObject(j).optString("nickname");
                                            communitySubClass.face = jsonArray1.optJSONObject(j).optString("face");
                                            comment_list.add(communitySubClass);
                                        }
                                        commentInfoList.commentSub_list = comment_list;
                                        commentInfoLists.add(commentInfoList);
                                    }
                                    if (commentunityInfoListAdapter != null) {
                                        commentunityInfoListAdapter.refresh(commentInfoLists);
                                    }
                                    communityDataLayout.setVisibility(View.VISIBLE);
                                    communityInoNodata.setVisibility(View.GONE);
                                } else {
                                    if (communityInfoList != null) {
                                        communityInfoList.onRefreshComplete();
                                    }
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                }

                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    if (communityInfoList != null) {
                        communityInfoList.onRefreshComplete();
                    }
                    communityDataLayout.setVisibility(View.GONE);
                    communityInoNodata.setVisibility(View.VISIBLE);
                }
            }
        });

    }




    //收藏
    private void CommunityCollect(String community_id) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("collect_id", community_id);
        OkHttpUtils.getInstance().postWithMemberToken(Url.COLLECT, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                if (jsonObject.optJSONObject("data").optInt("is_collect") == 1) {
                                    getCommunityInfo();
                                    EventBus.getDefault().post(new RfreshFavorites());
                                    EventBus.getDefault().post(new RfreshCommunity());
                                    EventBus.getDefault().post(new RfreshQuestion());
                                    EventBus.getDefault().post(new RfreshAnswer());
                                } else {
                                    getCommunityInfo();
                                    EventBus.getDefault().post(new RfreshFavorites());
                                    EventBus.getDefault().post(new RfreshCommunity());
                                    EventBus.getDefault().post(new RfreshQuestion());
                                    EventBus.getDefault().post(new RfreshAnswer());
                                }
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });

    }

    private void ReplyComment(final String community_id, final String comment_pid, String replyNames) {
        final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(CommuntiyInfoActivity.this, R.style.BottomSheetStyle);
        View view = LayoutInflater.from(CommuntiyInfoActivity.this).inflate(R.layout.dialog_input_reply, null);
        final EditText input = view.findViewById(R.id.reply_content);
        final Button yes_dialog = view.findViewById(R.id.reply_btn);
        final Button cancel_dialog = view.findViewById(R.id.cancel_btn);
        input.setHint(getString(R.string.reply) + "  " + replyNames + ":");
        input.setMovementMethod(new ScrollingMovementMethod());
        yes_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtils.isEmpty(input.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.please_input_reply_content));
                } else {
                    bottomSheetDialog.dismiss();
                    insertComment(input, community_id, comment_pid);
                }
            }
        });
        cancel_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
            }
        });
        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.setCanceledOnTouchOutside(true);
        if (!MyUtil.getActivity(bottomSheetDialog.getContext()).isFinishing()) {
            bottomSheetDialog.show();
        }

    }

    private void insertComment(EditText input, String community_id, String comment_pid) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("community_id", community_id);
        jsonObject.addProperty("contents", input.getText().toString().trim());
        jsonObject.addProperty("comment_pid", comment_pid);
        OkHttpUtils.getInstance().postWithMemberToken(Url.INSERTCOMMON, jsonObject.toString(), new OkHttpUtils.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                                EventBus.getDefault().post(new RfreshFavorites());
                                EventBus.getDefault().post(new RfreshCommunity());
                                EventBus.getDefault().post(new RfreshQuestion());
                                EventBus.getDefault().post(new RfreshAnswer());
                                getCommentList(true);
                                getCommunityInfo();
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }

    /**
     * facebook配置
     */
    private void initFacebook() {
        callbackManager = CallbackManager.Factory.create();
        shareDialog = new ShareDialog(this);
        // this part is optional
        shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {

            @Override
            public void onSuccess(Sharer.Result result) {
                //分享成功的回调，在这里做一些自己的逻辑处理
                ToastUtil.showToast("Share Success");
                EventBus.getDefault().post(new RfreshFavorites());
                EventBus.getDefault().post(new RfreshCommunity());
                EventBus.getDefault().post(new RfreshQuestion());
                EventBus.getDefault().post(new RfreshAnswer());
                getCommentList(true);
                getCommunityInfo();
            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onError(FacebookException error) {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //facebook的界面回调
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }


    @OnClick({R.id.back, R.id.share_layout, R.id.like_layout, R.id.reply_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.share_layout:
                final BottomSheetDialog bottomSheetDialog=new BottomSheetDialog(CommuntiyInfoActivity.this);
                View showThanksMoneyview = LayoutInflater.from(CommuntiyInfoActivity.this).inflate(R.layout.dialog_invite_friends, null);
                Button cancelBtn=showThanksMoneyview.findViewById(R.id.cancel);
                LinearLayout facebookLayout=showThanksMoneyview.findViewById(R.id.facebook_layout);
                LinearLayout twitterLayout=showThanksMoneyview.findViewById(R.id.twitter_layout);
                facebookLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomSheetDialog.dismiss();
                        if (!MyUtil.checkfackboosInstalled(CommuntiyInfoActivity.this)) {
                            ToastUtil.showToast(getString(R.string.please_install_facebook));
                            return;
                        }
                        if (ShareDialog.canShow(ShareLinkContent.class)) {
                            ShareLinkContent linkContent = new ShareLinkContent.Builder()
                                    .setContentUrl(Uri.parse("https://developers.facebook.com"))
                                    .build();
                            shareDialog.show(linkContent);
                        }
                    }
                });
                twitterLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomSheetDialog.dismiss();
                        if (!MyUtil.checkfackboosInstalled(CommuntiyInfoActivity.this)) {
                            ToastUtil.showToast(getString(R.string.please_install_twitter));
                            return;
                        }
                        try {
                            TweetComposer.Builder builder = new TweetComposer.Builder(CommuntiyInfoActivity.this)
                                    .url(new URL("https://www.google.com/"));
                            builder.show();
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        }
                    }
                });
                cancelBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomSheetDialog.dismiss();
                    }
                });
                bottomSheetDialog.setContentView(showThanksMoneyview);
                bottomSheetDialog.setCanceledOnTouchOutside(true);
                if (!MyUtil.getActivity(bottomSheetDialog.getContext()).isFinishing()) {
                    bottomSheetDialog.show();
                }
                break;
            case R.id.like_layout:
                CommunityCollect(community_id);
                break;


            case R.id.reply_btn:
                showReplyDialog();
                break;

            default:
                break;
        }
    }

    private void showReplyDialog() {
        final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(CommuntiyInfoActivity.this, R.style.BottomSheetStyle);
        View view = LayoutInflater.from(CommuntiyInfoActivity.this).inflate(R.layout.dialog_input_reply, null);
        final EditText input = view.findViewById(R.id.reply_content);
        final Button yes_dialog = view.findViewById(R.id.reply_btn);
        final Button cancel_dialog = view.findViewById(R.id.cancel_btn);
        input.setMovementMethod(new ScrollingMovementMethod());
        yes_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtils.isEmpty(input.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.please_input_reply_content));
                } else {
                    bottomSheetDialog.dismiss();
                    ReplyCommentPost(input, community_id);
                }
            }
        });
        cancel_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
            }
        });
        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.setCanceledOnTouchOutside(true);
        if (!MyUtil.getActivity(bottomSheetDialog.getContext()).isFinishing()) {
            bottomSheetDialog.show();
        }
    }

    private void ReplyCommentPost(EditText input, String community_id) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("community_id", community_id);
        jsonObject.addProperty("contents", input.getText().toString().trim());
        OkHttpUtils.getInstance().postWithMemberToken(Url.INSERTCOMMON, jsonObject.toString(), new OkHttpUtils.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                                EventBus.getDefault().post(new RfreshFavorites());
                                EventBus.getDefault().post(new RfreshCommunity());
                                EventBus.getDefault().post(new RfreshQuestion());
                                EventBus.getDefault().post(new RfreshAnswer());
                                getCommentList(true);
                                getCommunityInfo();
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClickImage(int position, String url, List<String> urlList) {
        List<String> temp = new ArrayList<>();
        for (int i = 0; i < urlList.size(); i++) {
            temp.add(urlList.get(i));
        }
        startActivity(new Intent(CommuntiyInfoActivity.this, BigImageActivity.class)
                .putStringArrayListExtra("data", (ArrayList<String>) temp)
                .putExtra("current", position));
    }
}
